<template>
  <swiper class="swiper-content" :current="currentTab" :duration="300" @change="switchTab">
    <swiper-item class="swiper-item-content" v-for="(dataList, idk) in resultData" :key="idk">
      <scroll-view scroll-y enableBackToTop="true" @scrolltolower="loadMore">
        <tui-list-view>
          <tui-list-cell
            :class-name="
                  'animated fadeInRight delay-z' +
                    (index - (dataList.pageIndex - 1) * 6) * 2
                "
            v-for="(item, index) in dataList.list"
            :key="index"
            :index="index"
            @click="detail"
          >
            <view class="tui-flex tui-flex-1">
              <image v-if="item.cover" mode="widthFix" :src="item.cover" style="width:150rpx;" />
              <view class="tui-flex-1 tui-flex tui-flex-column" style="padding-left:20rpx;">
                <view class="tui-flex">
                  <view class="tui-flex-1" style="font-weight:bold;font-size:38rpx;">{{ item.name }}</view>
                  <tui-button
                    v-if="showButton"
                    size="small"
                    :disabled="item.inBookshelf"
                    :type="item.inBookshelf ? 'gray' : 'warning'"
                    :loading="item.loading"
                    :stop="true"
                    @click="addBookshelf(index)"
                  >{{ item.inBookshelf ? "已添加" : "加备用源" }}</tui-button>
                </view>
                <view class="tui-flex" style="font-size:28rpx;">
                  <view class="tui-flex-1">
                    <tui-icon name="people" :size="28" :rpx="true" color="#6cc" />
                    {{ " " + item.author }}
                  </view>
                  <view style="color:#ccc;font-size:26rpx;">
                    <text v-if="item.status">{{ item.status }} |</text>
                    {{ item.category || "" }}
                  </view>
                </view>
                <view
                  v-if="item.latest_chapter_name"
                  class="tui-flex"
                  style="color:#555;font-size:26rpx;"
                >最新章节：{{ item.latest_chapter_name }}</view>
                <view
                  v-if="item.update_time"
                  class="tui-flex"
                  style="color:#555;font-size:26rpx;"
                >更新时间：{{ item.update_time }}</view>
                <view class="story-description">{{ item.description }}</view>
              </view>
            </view>
          </tui-list-cell>
        </tui-list-view>
        <tui-loadmore :visible="dataList.loadding"></tui-loadmore>
        <tui-nomore :visible="!dataList.hasMore"></tui-nomore>
      </scroll-view>
    </swiper-item>
  </swiper>
</template>

<script>
import tuiIcon from "@/components/icon/icon";
import tuiButton from "@/components/button/button.vue";
import tuiListView from "@/components/list-view/list-view.vue";
import tuiListCell from "@/components/list-cell/list-cell.vue";
import { equalUrl } from "@/utils/util";

export default {
  components: { tuiIcon, tuiButton, tuiListView, tuiListCell },
  props: {
    currentTab: {
      type: Number,
      default: 0
    },
    value: {
      type: String,
      default: ""
    },
    showButton: {
      type: Boolean,
      default: false
    },
    sources: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      resultData: []
    };
  },
  methods: {
    loadMore() {
      const { loadData, hasMore } = this.resultData[this.currentTab];
      if (loadData.length > 0) {
        // 已预加载完毕，直接追加列表，并预加载下一页
        this.resultData[this.currentTab].pageIndex++;
        this.resultData[this.currentTab].list.push(...loadData);
        if (loadData.length < this.sources[this.currentTab].pageSize) {
          this.resultData[this.currentTab].hasMore = false;
          this.resultData[this.currentTab].loadData = [];
        } else {
          this.preLoad(this.currentTab);
        }
      } else if (hasMore) {
        // 标记已触过底，等待预加载完毕后，立即追加
        this.resultData[this.currentTab].loadding = true;
      }
    },
    // 预加载
    preLoad(currentTab = this.currentTab) {
      this.resultData[currentTab].loadData = [];
      this.searchItem(
        this.resultData[currentTab].pageIndex + 1,
        this.sources[currentTab]._id
      ).then(data => {
        if (this.resultData[currentTab].loadding) {
          this.resultData[currentTab].pageIndex++;
          this.resultData[currentTab].list.push(...data);
          this.resultData[currentTab].loadding = false;
          if (data.length < this.sources[currentTab].pageSize) {
            this.resultData[currentTab].hasMore = false;
          } else {
            this.preLoad(currentTab);
          }
        } else {
          // 还没有触底，先把预加载的数据储存，不追加列表
          this.resultData[currentTab].loadData = data;
        }
      });
    },
    search(reinit = true) {
      if (!this.sources[this.currentTab]._id) {
        this.tui.toast("没有选择源");
        return;
      }
      const value = this.key;
      if (!value) {
        this.tui.toast("请输入搜索内容");
      } else {
        if (reinit) this.initReuslt();
        this.pageLoadding = true;
        const index = this.history.indexOf(value);
        if (index > -1) {
          this.history.splice(index, 1);
        }
        this.history.unshift(value);

        this.searchItem()
          .then(data => {
            // console.log(data, this.resultData, this.currentTab);
            this.resultData[this.currentTab].list = data;
            if (data.length < this.sources[this.currentTab].pageSize) {
              this.resultData[this.currentTab].hasMore = false;
            } else {
              this.resultData[this.currentTab].hasMore = true;
              this.preLoad(this.currentTab);
            }
            this.showResult = true;
            this.pageLoadding = false;
          })
          .catch(err => {
            const error = JSON.stringify(err);
            if (error.indexOf("exection timeout")) {
              this.tui.toast("请求超时了");
            } else {
              this.tui.toast("发生错误了");
            }
            console.log(JSON.stringify(err));
            this.pageLoadding = false;
          });
      }
    },
    // 由于小程序云开发最长20s请求超时，所以一页中的数据分多次请求
    async searchItem(
      pageIndex = this.resultData[this.currentTab].pageIndex,
      source_id = this.sources[this.currentTab]._id
    ) {
      const data = [];
      const res = await this.callFunc({
        name: "search",
        data: {
          source_id,
          value: this.key,
          pageIndex
        }
      });
      if (res.result && res.result.errMsg == "ok") {
        res.result.data.forEach(item => {
          item.inBookshelf = this.isInBookshelf(item);
          data.push(item);
        });
      } else {
        this.tui.toast(res.result.errMsg);
      }
      // console.log(data);
      return data;
    },
    // 是否在书架中
    isInBookshelf(item) {
      const book = this.bookshelfs.find(
        bs => bs.name == item.name && bs.author == item.author
      );
      if (!book) {
        return 0;
      }
      if (
        book.source_id == item.source_id &&
        equalUrl(book.read_url, item.read_url)
      ) {
        return 1;
      } else if (
        book.other_sources &&
        book.other_sources.some(
          os =>
            os.source_id == item.source_id &&
            equalUrl(os.read_url, item.read_url)
        )
      ) {
        return 1;
      }
      return -1;
    },
    detail({ index }) {
      const { source_id, read_url } = this.resultData[this.currentTab].list[
        index
      ];
      uni.navigateTo({
        url:
          "/pages/detail/detail?source_id=" +
          source_id +
          "&read_url=" +
          read_url
      });
    },
    switchTab(e) {
      if (!e.detail.source) {
        return;
      }
      this.currentTab = e.detail.current;
      if (
        this.resultData[this.currentTab].hasMore &&
        !this.resultData[this.currentTab].loading
      ) {
        this.search(this.currentTab);
      }
      this.$nextTick(() => this.checkCor(this.scrollLeft));
    }
  }
};
</script>

<style>
.swiper-content {
  height: 100%;
}

.swiper-item-content {
  display: flex;
  flex: 1;
  position: absolute;
  width: 100%;
  height: 100%;
  transform: translate(0%, 0px) translateZ(0px);
}
</style>